var fs = require('fs');

function DmaArea(list){
    this.list = list.sort(function(a,b){
        return a.x - b.x
    })
    this.getRectPoints(this.list)
}
DmaArea.prototype.init = function(){
    //初始化
}
//计算向量夹角
DmaArea.prototype.angle = function(p1,p2,p3){
    var a,b,ab

    a = Math.sqrt(Math.pow(p1.x - p2.x,2) + Math.pow(p1.y - p2.y,2))
    b = Math.sqrt(Math.pow(p3.x - p2.x,2) + Math.pow(p3.y - p2.y,2))
    ab = (p1.x - p2.x)*(p3.x - p2.x)+(p1.y - p2.y)*(p3.y - p2.y)

    return Math.acos(ab/(a*b))*180/Math.PI
}
//遍历所有点，找出最大矩形
DmaArea.prototype.loopNext = function (points,list){
    var len = points.length,arr = [],an,max = 0,next

    for(var i = 0;i < list.length;i++){
        an = this.angle(points[len - 2],points[len - 1],list[i])
        if(an > max){
            max = an
            next = i
        }
    }
    if(len >= 3){
        an = this.angle(points[len - 2],points[len - 1],points[0])
        if(an > max){
            return
        }
    }
    list.map(function(e,index){
        if(index != next){
            arr.push(e)
        }
    })
    points.push(list[next])
    this.loopNext(points,arr)
}
//判断点是否在矩形区域内
DmaArea.prototype.pointInArea = function(p, poly) {
    var flag = false
 
    for(var i = 0, l = poly.length, j = l - 1; i < l; j = i, i++) {
      var sx = poly[i].x,
          sy = poly[i].y,
          tx = poly[j].x,
          ty = poly[j].y
 
      // 点与多边形顶点重合
      if((sx === p.x && sy === p.y) || (tx === p.x && ty === p.y)) {
        return 'on'
      }
 
      // 判断线段两端点是否在射线两侧
      if((sy < p.y && ty >= p.y) || (sy >= p.y && ty < p.y)) {
        // 线段上与射线 Y 坐标相同的点的 X 坐标
        var x = sx + (p.y - sy) * (tx - sx) / (ty - sy)
        // 点在多边形的边上
        if(x === p.x) {
          return 'on'
        }
        // 射线穿过多边形的边界
        if(x > p.x) {
          flag = !flag
        }
      }
    }
    // 射线穿过多边形边界的次数为奇数时点在多边形内
    return flag ? 'in' : 'out'
}
DmaArea.prototype.getRectPoints = function (points){
    var p = [],list = []
    p.push(points[0],points[1])
    for(var i = 2;i<points.length ;i++){
        list.push(points[i])
    }
    this.loopNext(p,list)
    //console.log(points)
    console.log(this.pointInArea({x:2,y:0},p))
    console.log(this.pointInArea({x:2,y:-2},p))
    console.log(this.pointInArea({x:4,y:2},p))
}
var arr = [{x:0,y:2},{x:3,y:2},{x:4,y:2},{x:2,y:3},{x:1,y:1},{x:4,y:-1},{x:3,y:0},{x:0,y:0},{x:1,y:-2},{x:2,y:-1}]
var dma = new DmaArea(arr)
